<?php
//$Id: app.php 496 2012-07-31 10:02:45Z tomqin@gmail.com $

/**
 * App ARESCMS框架入口文件
 *
 * @copyright       Copyright (C) 2010-2012 ARESCMS Inc.
 * @author          TomQin <tomqin@gmail.com>
 * @license         http://www.arescms.cn/license/
 * @package Core
 */

require dirname(__FILE__).'/function/global.func.php';

//设置错误信息
error_reporting(E_ALL ^ E_NOTICE);
error_reporting(E_ALL);

//框架标记
define('DS', DIRECTORY_SEPARATOR);
define('IN_ARESCMS', true);

//系统路径
define('ARESCMS_ROOT', substr(__FILE__, 0, -14));
define('SYSTEM_DIR',   ARESCMS_ROOT.'system'.DS);
define('DATA_DIR',     ARESCMS_ROOT.'data'.DS);
define('STATIC_URL',   App::getConfig('system.static_url'));
define('UPLOAD_URL',   App::getConfig('system.upload_url'));
define('UPLOAD_DIR',   App::getConfig('system.upload_dir'));

//define('ADMIN_STATIC_URL', 'http://www.jlio.gov.cn/statics/'); //gbk
//define('ADMIN_STATIC_URL', 'http://www.upln.cn/statics/'); //utf8
define('ADMIN_STATIC_URL', 'http://localhost/phpcms9/statics/');

//主机协议,来源
define('SITE_PROTOCOL', isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://');
define('HTTP_REFERER', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '');
define('SITE_URL', (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''));

//系统开始时间
define('SYS_START_TIME', microtime(true));
define('TIMESTAMP', $_SERVER['REQUEST_TIME']);

//set_error_handler('my_error_handler');

date_default_timezone_set(App::getConfig('system.timezone'));
define('CHARSET', App::getConfig('system.charset'));


//输出页面字符集
header('Content-type: text/html; charset='.CHARSET);
/*
//GZIP 输出模式
if (App::getConfig('system.gzip') && function_exists('ob_gzhandler')) {
    ob_start('ob_gzhandler');
} else {
    ob_start();
}
*/

spl_autoload_register(array('App', 'autoLoad'));

// $Id: app.php 496 2012-07-31 10:02:45Z tomqin@gmail.com $

/**
 * App 应用程序框架基本操作类
 *
 * @copyright       Copyright (C) 2010-2012 ARESCMS Inc.
 * @author          TomQin <tomqin@gmail.com>
 * @license         http://www.arescms.cn/license/
 * @package Core
 */

class App
{
    /**
     * Cookie 设置
     */
    public static function updateCookie($name, $minutes = 0, $path = '/', $domain = null, $secure = false, $http_only = false){
        $value = self::getCookie($name);
        return self::setCookie($name, $value, $minutes, $path, $domain, $secure, $http_only);
    }

    public static function getCookie($name, $default = null){
        return (isset($_COOKIE[$name]) && $_COOKIE[$name]) ? $_COOKIE[$name] : $default;
    }

    public static function setCookie($name, $value, $minutes = 0, $path = '/', $domain = null, $secure = false, $http_only = false){
        if (headers_sent()) return false;

        $time = ($minutes !== 0) ? $_SERVER['REQUEST_TIME'] + ($minutes * 60) : 0;
        if ($minutes < 0){
            unset($_COOKIE[$name]);
        }else{
            $_COOKIE[$name] = $value;
        }

        return setcookie($name, $value, $time, $path, $domain, $secure, $http_only);
    }

    /**
     * 配置信息
     */
    private static $configs = array();

    public static function getConfig($name, $default = null){
        if(empty(self::$configs)) {
            self::initConfig();
        }
        if(empty($name)){
            return self::$configs;
        }else{
            return isset(self::$configs[$name]) ? self::$configs[$name] : $default;
        }
    }

    public static function initConfig(){
        self::$configs = require(DATA_DIR . 'config.inc.php');

        $city = substr($_SERVER['HTTP_HOST'], 0, -13); // strlen('.sudingke.com')
        if(isset(self::$configs['cities'][$city])){
            self::$configs['current.city'] = self::$configs['cities'][$city];
            App::setCookie('SudingkeCity', $city, 60, '/', '.sudingke.com');
        }else{//自动导航
            $city = App::getCookie('SudingkeCity');
            if(!isset(self::$configs['cities'][$city]))
                $city = 'dl';
            header('Location: http://'.$city.'.sudingke.com'.$_SERVER['REQUEST_URI']);
            exit();
        }
    }

    public static function getCityId(){
        return self::$configs['current.city'][0];
    }

    public static function getCityName(){
        return self::$configs['current.city'][1];
    }

    public static function getCityPerfix(){
        return self::$configs['current.city'][2];
    }

    /**
     * 获取客户端 IP 地址
     */
    public static function getClientIp(){
        $ip = $_SERVER['REMOTE_ADDR'];
        if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^(\d{1,3}\.){3}\d{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
            foreach ($matches[0] AS $xip) {
                if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                    $ip = $xip;
                    break;
                }
            }
        }
        return $ip;
    }

    /**
     * 载入文件
         class      db/mysqli.php           Db_Myqli
         class      action/front.php        Action_Front
         action     front/setting_db.php    Setting_Db_Action
         action     admin/hotel_hall.php    Hotel_Hall_Action
         action     test.php                Test_Action
         moudle     table/hotel.php         Table_Hotel_Moudle
         moudle     table/hotel_menu.php    Table_Hotel_Menu_Moudle
         moudle     hotel.php               Hotel_Moudle
         moudle     hotel/menu.php          Hotel_Menu_Moudle
     */
    public static function import($file) {
        if(is_file($file)) {
            include_once $file;
        } else {
            throw new Exception('Oops! System file lost: '.$file);
        }
        return true;
    }

    private static $objects = array();

    public static function module($name, $path = '', $init = array()){
        return self::load_class('module', ($path ? $path.'/'.$name : $name), true, $init);
    }

    public static function action($name, $path = '', $init = array()){
        return self::load_class('action', ($path ? $path.'/'.$name : $name), true, $init);
    }

    //仅限于 class
    public static function autoLoad($name){
        self::import(SYSTEM_DIR . 'class' .DS. str_replace('_', DS, strtolower($name)) . '.php');
    }

    private static function load_class($type, $name, $auto = false, $init = array()){
        if(in_array($type, array('module', 'action'))){
            $class = basename($name) . "_{$type}";
            $file  = SYSTEM_DIR. $type .DS. strtolower($name) . '.php';
        }else{
            throw new Exception('Oops! Wrong class type: '.$type);
        }
        if(!class_exists($class, false)){
            self::import($file);
        }

        if($auto){
            /**
             * see http://www.phpeye.com/feedentry/viewen/id/9238
             */
            switch(count($init)) {
                case 0:
                  $object = new $class();break;
                case 1:
                  $object = new $class($init[0]);break;
                case 2:
                  $object = new $class($init[0],$init[1]);break;
                case 3:
                  $object = new $class($init[0],$init[1],$init[2]);break;
                case 4:
                  $object = new $class($init[0],$init[1],$init[2],$init[3]);break;
                default:
                  throw new Exception('Oops! Too many args, less than 4 args!');
             }
             //self::$objects[$class] = $object;
             return $object;
        }else{
            return true;
        }
    }

    public static function run(){
        App::initConfig();

        $param1 = $param2 = '';
        $base = 'front';
        if(isset($_SERVER['REDIRECT_URL'])){
            if(preg_match('/^\/(admin|member)\/?/', $_SERVER['REDIRECT_URL'], $match)){
                @list( , , $act, $param1, $param2) = explode('/', $_SERVER['REDIRECT_URL'], 5);
                $base = $match[1];
                define('IN_ADMIN', true);
            }else{
                @list( , $act, $param1, $param2) = explode('/', $_SERVER['REDIRECT_URL'], 4);
            }
        }
        $act  = empty($act)  ? 'default' : $act;

        try{
            //init db;
            Db::instance(App::getConfig('database.default'));

            $action = App::action($act, $base);
            $action->initialize($act, $param1, $param2);
            $action->process();
        }catch(Exception $err){
            echo('页面不存在或者发生了一个错误，请稍候再试！<a href="/">返回首页</a>');
            echo('<script src="http://s4.cnzz.com/stat.php?id=995677&web_id=995677&show=pic1" language="JavaScript"></script>');
            echo '<h4>'.$err->getMessage().'</h4>';
            echo '<!--';
            print_r($err->getTrace());
            echo '-->';
            exit;
        }
    }
}

?>